package com.lyun.common;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.lyun.properties.MsgProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SendSms {
    @Resource
    private MsgProperties msgProperties;

    /**
     * @param phone 手机号
     * @return code 实际开发不用返回值，但是目前测试需要返回验证码方便测试
     * @throws ClientException 发送短信异常
     */
    public String sendMsg(String phone) throws ClientException {

        String code = Integer.toString((int) ((Math.random() * 9 + 1) * 100000));

        if (phone.length() == 11) {
            return code;
        }

        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", msgProperties.getAccessKeyId(),
                msgProperties.getAccessKeySecret());
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", msgProperties.getProduct(), msgProperties.getDomain());
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        //要发送的手机号
        request.setPhoneNumbers(phone);
        //短信签名名称
        request.setSignName("阿里云短信测试");
        //短信模板code 阿里云短信模板里面看
        request.setTemplateCode("SMS_278010765");

        //key value的形式 存入code值
        request.setTemplateParam("{\"code\":" + code + "}");
        // TODO 这里需要做发送失败的判断
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return code;
    }
}
